package sg.edu.nus.iss.vmcs.controller;

import sg.edu.nus.iss.vmcs.entity.Coin;
import sg.edu.nus.iss.vmcs.entity.Store;
import sg.edu.nus.iss.vmcs.entity.StoreItem;
import sg.edu.nus.iss.vmcs.util.VMCSException;
/**
 * ConcreateStrategyA
 * @author Cuong
 *
 */
public class LargestFirstChangeGiverStrategy implements ChangeGiverStrategy {
	public double giveChange(double changeAmt, MainController mainController){
		StoreController storeController = mainController.getStoreController();
		StoreItem[] storeItems = storeController.getStoreItems(Store.CASH);
//		for (int idx = 0; idx < storeItems.length; idx++) {
		for (int idx=storeItems.length - 1; idx >=0; idx--) {
			StoreItem storeItem = storeItems[idx];
			int quant = storeItem.getQuantity();
			Coin coin = (Coin)storeItem.getContent();
			double value = coin.getValue();
			//System.out.println("value: " + value + ", quantity: " + quant + ", changeGivenAmt: " + changeAmt);
			// if the change is more than change given amount,
			
			if (changeAmt + eps < value) {
				continue;
			}
			// empty change 
			if (quant < 1) {
				continue;
			}
			int numOfCoins = 0;
			for (int i=0; i<quant; i++) {
				if (changeAmt + eps < value) {
					break;
				}
				numOfCoins++;
				changeAmt = changeAmt - value;
			}
			/*
			 * start the give change sequence
			 */
			if (numOfCoins > 0) {
				MachineryController machineryController = mainController.getMachineryController();
				try {
					machineryController.giveChange(idx, numOfCoins);
					//System.out.println("after giving change, the number of coins remained: " + storeItem.getQuantity());
				} catch (VMCSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		return changeAmt;
	}
}
